<template>
  <div class="box" ref="targetElement">
    <div class="search-box" ref="searchBox">
      <div class="search-top-box">
        <div class="search-top-left-box">
          <el-form label-width="130px" ref="div" :inline="true" :model="formSearch" @submit.native.prevent
            class="demo-form-inline">
            <el-form-item label="项目名称">
              <el-input @change="onSearch" clearable class="form-width" v-model="formSearch.project_name"
                placeholder="输入项目名称"></el-input>
            </el-form-item>
            <el-form-item label="项目品牌">
              <el-select filterable @change="onSearch(1)" clearable class="form-width" v-model="formSearch.brand_id"
                placeholder="选择项目品牌">
                <el-option v-for="item in brandList" :key="item.id" :label="item.name" :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="创建人">
              <el-select filterable @change="onSearch(1)" clearable class="form-width"
                v-model="formSearch.handlers_name" placeholder="选择创建人">
                <el-option v-for="item in adminList" :key="item.id" :label="item.name" :value="item.name">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="创建时间">
              <el-date-picker value-format="yyyy-MM-dd" @change="onSearch(1)" clearable class="form-width"
                v-model="formSearch.created_at" type="daterange" range-separator="至" start-placeholder="开始日期"
                end-placeholder="结束日期">
              </el-date-picker>
            </el-form-item>
            <template v-if="moreSearchShow">
              <el-form-item label="项目编号">
                <el-input @change="onSearch" clearable class="form-width" v-model="formSearch.project_number"
                  placeholder="输入项目编号"></el-input>
              </el-form-item>
              <el-form-item label="项目类型">
                <el-select filterable @change="onSearch(1)" clearable class="form-width"
                  v-model="formSearch.store_type_id" placeholder="选择项目类型">
                  <el-option v-for="item in storeTypeList" :key="item.id" :label="item.store_type_name"
                    :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="风险标签">
                <el-select filterable @change="onSearch(1)" clearable class="form-width" v-model="formSearch.risk_label"
                  placeholder="选择风险标签">
                  <el-option label="一次预警" value="一次预警"></el-option>
                  <el-option label="二次预警" value="二次预警"></el-option>
                  <el-option label="已超期" value="已超期"></el-option>
                  <el-option label="停工" value="停工"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="施工阶段">
                <el-select filterable @change="onSearch(1)" clearable class="form-width"
                  v-model="formSearch.construction_stage_id" placeholder="选择施工阶段">
                  <el-option v-for="item in constructionStageList" :key="item.id" :label="item.name" :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="施工内容">
                <el-input @change="onSearch" clearable class="form-width" v-model="formSearch.content"
                  placeholder="输入施工内容"></el-input>
              </el-form-item>
              <el-form-item label="是否超期">
                <el-select filterable @change="onSearch(1)" clearable class="form-width" v-model="formSearch.is_overdue"
                  placeholder="选择是否超期">
                  <el-option label="是" :value="1"></el-option>
                  <el-option label="否" :value="2"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="超期类型">
                <el-select filterable @change="onSearch(1)" clearable class="form-width"
                  v-model="formSearch.overdue_type_id" placeholder="选择超期类型">
                  <el-option v-for="item in overdueTypeList" :key="item.id" :label="item.name" :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="预计完工日期">
                <el-date-picker value-format="yyyy-MM-dd" @change="onSearch(1)" clearable class="form-width"
                  v-model="formSearch.estimated_completion_date" type="daterange" range-separator="至"
                  start-placeholder="开始日期" end-placeholder="结束日期">
                </el-date-picker>
              </el-form-item>
            </template>
          </el-form>
        </div>
        <div class="search-top-right-box">
          <p @click="moreSearchFunc">
            {{ moreSearchShow ? "收起" : "展开"
            }}<i :class="moreSearchShow ? 'el-icon-arrow-up' : 'el-icon-arrow-down'
              "></i>
          </p>
          <el-button type="primary" @click="onSearch">查询</el-button>
          <el-button type="primary" :disabled="tableData.length == 0" @click="exportVisible = true"
            v-if="$isPer(permission, ['engineering_exportConstructionLogExcel'])">导出日志列表</el-button>
          <el-button type="primary" @click="addSgRzFunc"
            v-if="$isPer(permission, ['constructionLog_add'])">新增施工日志</el-button>
        </div>
      </div>
    </div>
    <!-- table -->
    <div class="page-list" ref="pageList">
      <div class="table-box" v-loading="pageLoading">
        <el-table border ref="table" :header-cell-style="{
          background: '#FAFBFC',
          color: '#828A9D',
          textAlign: 'center',
        }" :cell-style="{ textAlign: 'center', color: '#1B2431' }" :data="tableData" height="100%">
          <el-table-column min-width="140px" prop="" label="ID">
            <template slot-scope="scope">
              <el-button v-if="$isPer(permission, ['constructionLog_detail'])" type="text"
                @click="goToDetail(scope.row)">{{ $assemblyListNo('SGRZ', scope.row.id) }}</el-button>
              <span v-else>{{ $assemblyListNo('SGRZ', scope.row.id) }}</span>
            </template>
          </el-table-column>
          <el-table-column v-if="$fieldShowFunc('rz_xmmc')" min-width="180px" prop="" label="项目名称"
            show-overflow-tooltip>
            <template slot-scope="scope">
              {{ scope.row.project_name || '--' }}
            </template>
          </el-table-column>
          <el-table-column v-if="$fieldShowFunc('rz_xmbh')" min-width="130px" prop="project_number" label="项目编号"
            show-overflow-tooltip>
          </el-table-column>
          <el-table-column v-if="$fieldShowFunc('rz_xmpp')" min-width="120px" prop="" label="项目品牌"
            show-overflow-tooltip>
            <template slot-scope="scope">
              <el-tag :color="`${scope.row.brand_colour}`" style="color: #ffffff;">
                {{ scope.row.brand_name }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column v-if="$fieldShowFunc('rz_xmlx')" min-width="120px" prop="" label="项目类型"
            show-overflow-tooltip>
            <template slot-scope="scope">
              {{ scope.row.store_type_name || '--' }}
            </template>
          </el-table-column>
          <el-table-column v-if="$fieldShowFunc('rz_fxbq')" min-width="100px" prop="risk_label" label="风险标签"
            show-overflow-tooltip>
            <template slot-scope="scope">
              {{ scope.row.risk_label || '--' }}
            </template>
          </el-table-column>
          <el-table-column v-if="$fieldShowFunc('rz_sgjd')" min-width="120px" prop="" label="施工阶段"
            show-overflow-tooltip>
            <template slot-scope="scope">
              {{ scope.row.construction_stage || '--' }}
            </template>
          </el-table-column>
          <el-table-column v-if="$fieldShowFunc('rz_sgnr')" min-width="180px" prop="" label="施工内容"
            show-overflow-tooltip>
            <template slot-scope="scope">
              {{ scope.row.content || '--' }}
            </template>
          </el-table-column>
          <el-table-column v-if="$fieldShowFunc('rz_sfcq')" min-width="90px" prop="" label="是否超期" show-overflow-tooltip>
            <template slot-scope="scope">
              {{ scope.row.is_overdue == 1 ? '是' : '否' }}
            </template>
          </el-table-column>
          <el-table-column v-if="$fieldShowFunc('rz_cqlx')" min-width="100px" prop="" label="超期类型"
            show-overflow-tooltip>
            <template slot-scope="scope">
              <span>{{ scope.row.overdue_type || '--' }}</span>
            </template>
          </el-table-column>
          <el-table-column v-if="$fieldShowFunc('rz_cqyy')" min-width="180px" prop="" label="超期原因"
            show-overflow-tooltip>
            <template slot-scope="scope">
              {{ scope.row.reason_overdue || '--' }}
            </template>
          </el-table-column>
          <el-table-column v-if="$fieldShowFunc('rz_yjwgrq')" min-width="120px" prop="" label="预计完工日期"
            show-overflow-tooltip>
            <template slot-scope="scope">
              {{ scope.row.estimated_completion_date || '--' }}
            </template>
          </el-table-column>
          <el-table-column v-if="$fieldShowFunc('rz_cjr')" min-width="120px" prop="" label="创建人" show-overflow-tooltip>
            <template slot-scope="scope">
              {{ scope.row.handlers_name || '--' }}
            </template>
          </el-table-column>
          <el-table-column v-if="$fieldShowFunc('rz_cjsj')" min-width="180px" prop="" label="创建时间"
            show-overflow-tooltip>
            <template slot-scope="scope">
              {{ scope.row.created_at || '--' }}
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="page-footer">
        <el-pagination class="el-pagination" @current-change="handleCurrentChange" :current-page="page" :page-size="num"
          @size-change="handleSizeChange" layout="total, sizes, prev, pager, next, jumper" :total="total">
        </el-pagination>
      </div>
    </div>
    <!-- 导出日志列表 -->
    <el-dialog :modal-append-to-body="false" title="导出日志字段选择" :visible.sync="exportVisible" width="680px"
      :before-close="exportCloseFunc">
      <el-checkbox class="checkbox-item" v-model="allChecked" @change="allCheckedChangeFunc">全选</el-checkbox>
      <div v-loading="exportLoading">
        <div class="export-scroll">
          <el-checkbox-group v-model="exportrVal">
            <el-checkbox class="checkbox-item" v-for="(item, index) in exportArr" :key="index" :label="item.label"
              border></el-checkbox>
          </el-checkbox-group>
        </div>
        <p v-if="exportUrl">导出文件链接：<el-button @click="$openUrlFunc(exportUrl[0])" type="text">{{
          exportUrl[1]
        }}</el-button></p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="exportSubmitFunc">提交</el-button>
        <el-button @click="exportCloseFunc">关闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import engineeringApi from "@/api/engineeringApi";
import { getUserInfo } from "@/utils/auth";
import brandApi from '@/api/brandApi';
import storeTypeApi from '@/api/storeTypeApi';
import adminApi from "@/api/adminApi";
import { exportConstructionLogFideldArr } from '@/utils/exportField'
import configApi from "@/api/configApi";
export default {
  name: "constructionLog",
  data() {
    return {
      // 导出用户列表
      allChecked: false,//是否全选字段
      exportLoading: false,//导出loading
      exportVisible: false,//导出弹窗
      exportUrl: '',//导出url
      exportrVal: [],//导出勾选字段
      exportArr: exportConstructionLogFideldArr,//导出字段数组


      userInfo: "",
      tableData: [],
      formSearch: {},
      moreSearchShow: false,
      page: 1,
      num: 10,
      total: 0,
      pageLoading: false,
      brandList: [],
      storeTypeList: [],
      adminList: [],//工程监理
      constructionStageList: [],//施工阶段
      overdueTypeList: [],//超期类型
      permission: [],//操作权限
    };
  },
  watch: {},
  computed: {},
  activated() {
    // 监听窗口大小变化事件
    window.addEventListener('resize', this.handleResize);
    this.onSearch();
  },
  destroyed() {
    window.removeEventListener('resize', this.handleResize);
    // 移除窗口大小变化事件监听器，防止内存泄漏
    if (this.resizeObserver) {
      // 停止观察目标元素，防止内存泄漏
      this.resizeObserver.disconnect();
    }
  },
  deactivated() {
    window.removeEventListener('resize', this.handleResize);
    // 移除窗口大小变化事件监听器，防止内存泄漏
    if (this.resizeObserver) {
      // 停止观察目标元素，防止内存泄漏
      this.resizeObserver.disconnect();
    }
  },
  mounted() {
    this.handleResize();
    // 监听窗口大小变化事件
    window.addEventListener('resize', this.handleResize);
    // 操作权限
    this.$getHtmlAuthority(this.$route.path).then(res => {
      console.log(res, "getHtmlAuthority");
      this.permission = res.data.permission;
    })
    this.userInfo = getUserInfo();

    this.constructionLogList();
    this.getBrandList();
    this.getStoreTypeList();
    this.getAdminList();
    this.getConstructionStage();
    this.getOverdueType();
  },
  methods: {
    handleResize() {
      const target = this.$refs.targetElement;
      const searchBox = this.$refs.searchBox;
      const pageList = this.$refs.pageList;
      // 创建 ResizeObserver 实例
      const resizeObserver = new ResizeObserver(entries => {
        setTimeout(() => {
          console.log('元素变为:', searchBox.offsetHeight);
          // searchBox.offsetHeight + 'px'
          pageList.style.height = 'calc(100% - ' + (searchBox.offsetHeight + 15) + 'px)';
        }, 0);
      });
      // 开始观察目标元素
      resizeObserver.observe(target);

      // 存储 resizeObserver 实例，以便在组件销毁时停止观察
      this.resizeObserver = resizeObserver;
    },
    // 超期类型
    getOverdueType() {
      configApi.getList({
        page: 1,
        num: 999
      }, 1).then(res => {
        console.log(res, "超期类型")
        if (res.code == 200) {
          this.overdueTypeList = res.data.list;
        }
      })
    },
    // 施工阶段
    getConstructionStage() {
      configApi.getList({
        page: 1,
        num: 999
      }, 0).then(res => {
        console.log(res, "施工阶段")
        if (res.code == 200) {
          this.constructionStageList = res.data.list;
        }
      })
    },
    // 导出列表确认
    exportSubmitFunc() {
      let exportrVal = this.exportrVal;//已勾选
      let exportArr = this.exportArr;//所有字段
      let formSearch = this.formSearch;//列表筛选项
      if (!exportrVal.length) {
        this.$message({
          type: 'warning',
          message: "请勾选需要导出的字段"
        })
        return;
      }
      let field_list = [];//提交列表
      exportrVal.forEach(item => {
        let index = exportArr.findIndex(child => {
          return item == child.label;
        })
        if (index != -1) {
          field_list.push(exportArr[index].value);
        }
      })
      this.exportConstructionLogExcel({
        field_list,
        project_name: formSearch.project_name || '',
        project_number: formSearch.project_number || '',
        brand_id: formSearch.brand_id || '',
        store_type_id: formSearch.store_type_id || '',
        risk_label: formSearch.risk_label || '',
        construction_stage_id: formSearch.construction_stage_id || '',
        is_overdue: formSearch.is_overdue || '',
        overdue_type_id: formSearch.overdue_type_id || '',
        estimated_completion_date_start: formSearch.estimated_completion_date ? formSearch.estimated_completion_date[0] : '',
        estimated_completion_date_end: formSearch.estimated_completion_date ? formSearch.estimated_completion_date[1] : '',
        content: formSearch.content || '',
        handlers_name: formSearch.handlers_name || '',
        overdue_completion_date_start: formSearch.overdue_completion_date ? formSearch.overdue_completion_date[0] : '',
        overdue_completion_date_end: formSearch.overdue_completion_date ? formSearch.overdue_completion_date[1] : '',
        created_at_start: formSearch.created_at ? formSearch.created_at[0] : '',
        created_at_end: formSearch.created_at ? formSearch.created_at[1] : '',
      })
    },
    exportConstructionLogExcel(obj) {
      this.exportLoading = true;
      engineeringApi.exportConstructionLogExcel(obj).then(res => {
        console.log(res, "导出工程日志列表")
        this.exportLoading = false;
        if (res.code == 200) {
          this.exportUrl = res.data;
        }
        this.$message({
          type: res.code == 200 ? 'success' : 'warning',
          message: res.message
        })
      })
    },
    // 导出字段全选
    allCheckedChangeFunc(e) {
      let exportrVal = [];
      console.log(e)
      let exportArr = this.exportArr;
      if (e) {
        exportArr.forEach(item => {
          exportrVal.push(item.label);
        })
        this.exportrVal = exportrVal//已选择字段
      } else {
        this.exportrVal = exportrVal//已选择字段
      }
    },
    // 关闭导出弹窗
    exportCloseFunc() {
      this.exportVisible = false;
      this.allChecked = false;
      this.exportrVal = [];
      this.exportUrl = '';
    },
    // 新增施工日志
    addSgRzFunc() {
      this.$store.commit('isEventTriggeredFunc', true);
      this.$router.push({
        path: "/addSgRz",
      })
    },
    // 工程监理
    getAdminList() {
      adminApi.getAdminList({
        page: 1,
        num: 9999,
        identity: 1,
        position_id_arr: [8]
      }).then(res => {
        console.log(res, "工程监理")
        if (res.code == 200) {
          this.adminList = res.data.list;
        }
      })
    },
    // 品牌列表
    getBrandList() {
      brandApi
        .getBrandList({
          page: 1,
          num: 9999,
          keyword: "",
        })
        .then((res) => {
          console.log(res, "品牌列表");
          if (res.code == 200) {
            this.brandList = res.data.list;
          }
        })
        .catch(() => { });
    },
    // 门店类型列表
    getStoreTypeList() {
      storeTypeApi.getStoreTypeList({
        page: 1,
        num: 999
      }).then(res => {
        console.log(res, "门店类型列表")
        if (res.code == 200) {
          this.storeTypeList = res.data.list;
        }
      })
    },
    // 施工日志列表
    constructionLogList() {
      this.pageLoading = true;
      let formSearch = this.formSearch;
      engineeringApi.constructionLogList({
        page: this.page,
        num: this.num,
        project_name: formSearch.project_name || '',
        project_number: formSearch.project_number || '',
        brand_id: formSearch.brand_id || '',
        store_type_id: formSearch.store_type_id || '',
        risk_label: formSearch.risk_label || '',
        construction_stage_id: formSearch.construction_stage_id || '',
        is_overdue: formSearch.is_overdue || '',
        overdue_type_id: formSearch.overdue_type_id || '',
        estimated_completion_date_start: formSearch.estimated_completion_date ? formSearch.estimated_completion_date[0] : '',
        estimated_completion_date_end: formSearch.estimated_completion_date ? formSearch.estimated_completion_date[1] : '',
        content: formSearch.content || '',
        handlers_name: formSearch.handlers_name || '',
        overdue_completion_date_start: formSearch.overdue_completion_date ? formSearch.overdue_completion_date[0] : '',
        overdue_completion_date_end: formSearch.overdue_completion_date ? formSearch.overdue_completion_date[1] : '',
        created_at_start: formSearch.created_at ? formSearch.created_at[0] : '',
        created_at_end: formSearch.created_at ? formSearch.created_at[1] : '',
      }).then(res => {
        console.log(res, "施工日志列表")
        this.pageLoading = false;
        if (res.code == 200) {
          this.tableData = res.data.list;
          this.total = res.data.max;
        }
      })
    },
    // 单页数据量修改
    handleSizeChange(e) {
      this.num = e;
      this.onSearch(1);
    },
    // 搜索
    onSearch(page) {
      this.page = typeof page == 'number' ? page : this.page;
      this.constructionLogList();
    },
    // 翻页
    handleCurrentChange(page) {
      this.onSearch(page);
    },
    moreSearchFunc() {
      this.moreSearchShow = !this.moreSearchShow;
      this.$nextTick(() => {
        this.handleResize();
      })
    },
    goToDetail(row) {
      this.$store.commit('isEventTriggeredFunc', true);
      this.$router.push({
        path: "/constructionLogDetailPage?id=" + row.id
      })
    },
  },
};
</script>

<style lang="scss" scoped>
@import "./index.scss";
@import '@/styles/listPage.scss'
</style>